package com.dudy.service.oa.leave;

import com.dudy.entity.Leave;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:wb-zhaojunwei@alibaba-inc.com">wb-zhaojunwei></a>
 * @version 1.0
 * @Description 类说明
 * @since 2016/3/10
 */
@Service
public class LeaveWorkflowService {

    @Resource
    private LeaveManager leaveManager;

    @Resource
    private IdentityService identityService;

    @Resource
    private TaskService taskService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private HistoryService historyService;

    /**
     * 开启流程
     *
     * @param leave
     * @return
     */
    @Transactional
    public ProcessInstance startWorkflow(Leave leave,Map<String, Object> variables) {
        leaveManager.saveLeave(leave);
        String businessKey = leave.getId().toString();
        // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
        ProcessInstance processInstance;
        try {
            identityService.setAuthenticatedUserId(leave.getUserId());
            processInstance = runtimeService.startProcessInstanceByKey("leave", businessKey,variables);
            String processInstanceId = processInstance.getProcessInstanceId();
            leave.setProcessInstanceId(processInstanceId);
        } finally {
            identityService.setAuthenticatedUserId(null);
        }
        return processInstance;
    }

    /**
     * 查询所有待办流程
     *
     * @param userId
     * @return
     */
    @Transactional
    public List<Leave> findTodoTasks(String userId) {
        List<Task> tasks = taskService.createTaskQuery().taskCandidateOrAssigned(userId).list();
        List<Leave> results = new ArrayList<Leave>();
        for (Task task : tasks) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
            String businessKey;
            if (processInstance == null) {
                businessKey = StringUtils.EMPTY;
            } else {
                businessKey = processInstance.getBusinessKey();
            }
            if (StringUtils.isBlank(businessKey)) {
                continue;
            }
            Leave leave = leaveManager.getLeave(Long.parseLong(businessKey));
            leave.setTask(task);
            leave.setProcessInstance(processInstance);
            leave.setProcessDefinition(this.finProcessDefinition(processInstance.getProcessDefinitionId()));
            results.add(leave);
        }
        return results;
    }

    /**
     * 查询所有的运行中流程
     *
     * @return
     */
    @Transactional
    public List<Leave> findRunningProcessInstaces() {
        List<Leave> results = new ArrayList<Leave>();
        List<ProcessInstance> lists = runtimeService.createProcessInstanceQuery().processDefinitionKey("leave").active().orderByProcessDefinitionId().desc().list();
        for (ProcessInstance processInstance : lists) {
            String businessKey = processInstance.getBusinessKey();
            if (StringUtils.isBlank(businessKey)) {
                continue;
            }
            Leave leave = leaveManager.getLeave(Long.parseLong(businessKey));
            leave.setProcessInstance(processInstance);
            leave.setProcessDefinition(this.finProcessDefinition(processInstance.getProcessDefinitionId()));
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).active().orderByTaskCreateTime().desc().list();
            leave.setTask(tasks.get(0));
            results.add(leave);
        }
        return results;
    }

    /**
     * 读取所有完成流程
     *
     * @return
     */
    public List<Leave> findFinishedProcessInstaces() {
        List<Leave> results = new ArrayList<Leave>();
        List<HistoricProcessInstance> lists = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("leave").finished().orderByProcessInstanceEndTime().desc().list();
        for (HistoricProcessInstance historicProcessInstance : lists) {
            String businessKey = historicProcessInstance.getBusinessKey();
            if (StringUtils.isBlank(businessKey)) {
                continue;
            }
            Leave leave = leaveManager.getLeave(Long.parseLong(businessKey));
            leave.setHistoricProcessInstance(historicProcessInstance);
            leave.setProcessDefinition(this.finProcessDefinition(historicProcessInstance.getProcessDefinitionId()));
            results.add(leave);
        }
        return results;
    }

    /**
     * 查询processDefinition 流程定义ID
     *
     * @param processDefinitionId
     * @return
     */
    public ProcessDefinition finProcessDefinition(String processDefinitionId) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
        return processDefinition;
    }
}
